package com.zpark;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * @PackageName: com.zpark
 * @ClassName: XPathParseXmlFileDemo
 * @Description: XPath解析器
 * @author: RZS
 * @date: 2021/8/15  20:46
 */
public class XPathParseXmlFileDemo {
    public static void main(String[] args) throws Exception {
        // 获取xml文件路径
        String path = XPathParseXmlFileDemo.class.getClassLoader().getResource("xpath.xml").getPath();
        // 由于路径中包含中文，所以需要对路径解析解码
        path = URLDecoder.decode(path, "utf-8");
        // 获取DocumentBuilderFactory对象
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        // 根据DocumentBuilderFactory对象,构建DocumentBuilder对象
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        // 根据DocumentBuidler对象,构建Document对象
        Document document = documentBuilder.parse(path);

        // 构建XPath
        XPath xPath = XPathFactory.newInstance().newXPath();

        // 准备路径表达式，并计算它
        String expression = "/class/student";
        NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(document, XPathConstants.NODESET);

        // 遍历节点列表
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node nNode = nodeList.item(i);
            System.out.println("\nCurrent Element :"
                    + nNode.getNodeName());
            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                Element eElement = (Element) nNode;
                System.out.println("Student roll no : "
                        + eElement.getAttribute("rollno"));
                System.out.println("First Name : "
                        + eElement
                        .getElementsByTagName("firstname")
                        .item(0)
                        .getTextContent());
                System.out.println("Last Name : "
                        + eElement
                        .getElementsByTagName("lastname")
                        .item(0)
                        .getTextContent());
                System.out.println("Nick Name : "
                        + eElement
                        .getElementsByTagName("nickname")
                        .item(0)
                        .getTextContent());
                System.out.println("Marks : "
                        + eElement
                        .getElementsByTagName("marks")
                        .item(0)
                        .getTextContent());
            }
        }
    }
}
